package com.spring.security.core.authorize;

import com.spring.security.core.properties.SecurityProperties;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TreeSet;

/**
 * 核心模块的授权配置提供器，安全模块涉及的url的授权配置在这里。
 *
 * @author_seabed_moon
 */
@Configuration
@Order(Integer.MIN_VALUE)
public class SpringAuthorizeConfigProvider implements AuthorizeConfigProvider {

    @Autowired
    private SecurityProperties securityProperties;

    /**
     * 核心配置
     *
     * @param config
     * @return
     */
    @Override
    public boolean config(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry config) {
        // # 放行白名单请求
        List<String> defaultUrlList = new ArrayList<>(Arrays.asList(securityProperties.getWhite().getDefaultUrls()));
        defaultUrlList.add(securityProperties.getBrowser().getSignInPage());
        defaultUrlList.add(securityProperties.getBrowser().getSignUpUrl());
        defaultUrlList.add(securityProperties.getBrowser().getSession().getSessionInvalidUrl());
        if (StringUtils.isNotBlank(securityProperties.getBrowser().getSignOutUrl())) {
            defaultUrlList.add(securityProperties.getBrowser().getSignOutUrl());
        }
        // 去重url
        TreeSet<String> whiteUrlSet = new TreeSet<>();
        whiteUrlSet.addAll(defaultUrlList);
        whiteUrlSet.addAll(Arrays.asList(securityProperties.getWhite().getUrls()));
        securityProperties.getWhite().allUrls = whiteUrlSet.toArray(new String[whiteUrlSet.size()]);
        config.antMatchers(securityProperties.getWhite().allUrls).permitAll();
        return false;
    }

}
